import time
from selenium import webdriver
from selenium.webdriver.common.by import By


def auto_buy(url, buy_time):
    driver = webdriver.Chrome()  # 使用Chrome浏览器，需要提前安装selenium和ChromeDriver
    driver.get(url)  # 打开商品页面
    driver.maximize_window()
    time.sleep(3)
    # 点击密码登录
    driver.find_element(By.XPATH, '/html/body/div[2]/div/div/div[1]/div/div[2]/span').click()
    time.sleep(2)
    # 输入用户名
    driver.find_element(By.XPATH, '/html/body/div[2]/div/div/form/div[1]/div/input').send_keys('18515986713')
    # 输入登录密码
    driver.find_element(By.XPATH, '/html/body/div[2]/div/div/form/div[2]/div/input').send_keys('QAZqaz,/@123')
    # 点击登录
    driver.find_element(By.XPATH, '/html/body/div[2]/div/div/form/div[3]/button').click()
    time.sleep(20)
    while True:
        current_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())  # 获取当前时间
        if current_time >= buy_time:
            try:
                # 刷新页面
                driver.refresh()
                time.sleep(3)
                # 点击全选
                driver.find_element(By.XPATH, '//*[@id="__layout"]/div/div[1]/div/div[3]/div/div[1]/label/span[1]').click()
                time.sleep(3)
                # 点击结算按钮
                driver.find_element(By.XPATH, '//*[@id="__layout"]/div/div[1]/div/div[3]/div/div[2]/div[2]/button').click()
                time.sleep(7)
                # 点击提交订单按钮
                driver.find_element(By.XPATH, '//*[@id="__layout"]/div/div[1]/div[3]/div/div[4]/div[4]/button').click()
                time.sleep(20)
                print('商品已成功抢购！')
                break
            except:
                print('抢购失败，请重试！')
                time.sleep(0.1)  # 如果抢购失败，等待0.1秒后重试
        else:
            print('还未到抢购时间，当前时间：', current_time)
            time.sleep(1)  # 每秒检查一次是否到了抢购时间

    time.sleep(10)  # 等待10秒后关闭浏览器
    driver.quit()


# 示例用法
url = 'https://www.mihoyogift.com/ys/cart?utm_source=bbs&utm_medium=mys&utm_campaign=arti'  # 商品页面的URL
buy_time = '2023-07-14 00:00:05'  # 抢购时间，格式为'YYYY-MM-DD HH:MM:SS'
auto_buy(url, buy_time)
